package com.avic.rong.activity.no;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Toast;

import com.avic.rong.BuildConfig;
import com.avic.rong.MyApplication;
import com.avic.rong.R;
import com.avic.rong.api.UpdateUserLogoApi;
import com.avic.rong.api.UploadPhotoApi;
import com.avic.rong.bean.LoginOutEvent;
import com.avic.rong.bean.NickNameEvent;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.wedgit.customWedgit.SheetDialog;
import com.avic.rong.wedgit.permissionschecker.PermissionChecker;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.orhanobut.logger.Logger;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.theartofdev.edmodo.cropper.PhotoUpdateEvent;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.werb.pickphotoview.CropImage;
import com.werb.pickphotoview.PickPhotoActivity;
import com.werb.pickphotoview.model.PickData;
import com.werb.pickphotoview.util.PickConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UserSetAccountActivity extends RxAppCompatActivity {


    private static final int TAKE_CAMERA_PHOTO = 200;
    public static String ARG_URL = "arg_url";

    @BindView(R.id.webview)
    BridgeWebView webView;

    private String path;
    String url = null;
    private boolean changeNickName = false;
    private PermissionChecker permissionChecker;
    private String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private boolean changePhoto = false;
    private SheetDialog sheetDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_detail);
        ButterKnife.bind(this);

        permissionChecker = new PermissionChecker(UserSetAccountActivity.this);

        if (getIntent() != null){
            url = getIntent().getStringExtra(ARG_URL);
        }

        if (!TextUtils.isEmpty(url)) {
            webView.loadUrl(url);
        }

        webView.registerHandler("pushVc", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                data = data.replace("\\", "");
                JsonObject jsonObject = (JsonObject) new JsonParser().parse(data);
                String userId = "";
                if (MyApplication.getInstance().userLoginBean != null) {
                    userId = String.valueOf(MyApplication.getInstance().userLoginBean.getUserId());
                }
                String urlString = jsonObject.get("url").getAsString();
                if (urlString.contains("member/setNickName")){//修改昵称
                    startActivityForResult(NickNameEditActivity.queryIntent(UserSetAccountActivity.this,urlString + "?userIdSign=" + userId),100);
                }else if(urlString.contains("member/modifyMobile")){//修改绑定手机
                    startActivityForResult(ModifyPhoneActivity.queryIntent(UserSetAccountActivity.this,urlString + "?userIdSign=" + userId),100);
                }else if(urlString.contains("member/modifyPwd")){//修改密码
                    startActivityForResult(ModifyPwdActivity.queryIntent(UserSetAccountActivity.this,urlString + "?userIdSign=" + userId),100);
                }else if(urlString.contains("member/setAccount1")){//完善个人信息
                    startActivityForResult(UserInfoCompleteActivity.queryIntent(UserSetAccountActivity.this,urlString + "?userIdSign=" + userId),100);
                }else if(urlString.contains("member/setPhotos")){//设置个人头像
                    setUserPhoto();
//                    startActivityForResult(UserPhotoActivity.queryIntent(UserSetAccountActivity.this,urlString + "?userIdSign=" + userId),100);
                }

            }
        });

        webView.registerHandler("goBack", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                finish();
            }
        });

        //退出登录
        webView.registerHandler("goLogout", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                MyApplication.getInstance().userLoginBean = null;
                SharedPreferencesUtil.getInstance().put(ConstantsUtils.USER_INFO, "");
                EventBus.getDefault().postSticky(new LoginOutEvent());

                CookieSyncManager.createInstance(UserSetAccountActivity.this);
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.removeAllCookie();
                CookieSyncManager.getInstance().sync();
                finish();
            }
        });
    }

    //修改个人头像
    private void setUserPhoto(){
        sheetDialog =  new SheetDialog.Builder(UserSetAccountActivity.this).setTitle(ConstantsUtils.EMPTY_STR)
                .addMenu("拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.cancel();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            path = SDCardUtils.getSDCardPath() + "/temp.png";
                            File file = new File(path);
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(UserSetAccountActivity.this,BuildConfig.APPLICATION_ID + ".fileProvider", file));
                            }else{
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            }

                            intent.putExtra("return-data", false);
                            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                            intent.putExtra("noFaceDetection", true);
                            startActivityForResult(intent, TAKE_CAMERA_PHOTO);
                        }
                    }
                })
                .addMenu("从相册中选择", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.cancel();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                           startPickPhoto();
                        }
                    }
                }).create();
        sheetDialog.show();
    }


    private void startPickPhoto() {
        PickData pickData = new PickData();
        pickData.setPickPhotoSize(1);
        pickData.setShowCamera(false);
        pickData.setSpanCount(4);
        Intent intent = new Intent();
        intent.setClass(this, PickPhotoActivity.class);
        intent.putExtra(PickConfig.INTENT_PICK_DATA, pickData);
        startActivityForResult(intent, PickConfig.PICK_PHOTO_DATA);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PermissionChecker.PERMISSION_REQUEST_CODE:
                if (permissionChecker.hasAllPermissionsGranted(grantResults)) {
                    if (sheetDialog != null && sheetDialog.isShowing()){
                        sheetDialog.cancel();
                    }
                    startPickPhoto();
                } else {
                    permissionChecker.showDialog();
                }
                break;
        }
    }


    /**
     * 修改头像
     *
     * @param updateEvent
     */
    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void updateUserPhotoEvent(PhotoUpdateEvent updateEvent) {
        try {

            String imagePath = updateEvent.getUrl();
            Bitmap bitmap = BitmapFactory.decodeFile(updateEvent.getUrl());
            Logger.i("--dd----size: " + bitmap.getByteCount() + " width: " + bitmap.getWidth() + " heigth:" + bitmap.getHeight()); // 输出图像数据
            UploadPhotoApi uploadPhotoApi = new UploadPhotoApi(this, uploadOnNextListener);

            // 设置参数
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; // 只获取图片的大小信息，而不是将整张图片载入在内存中，避免内存溢出
            BitmapFactory.decodeFile(imagePath, options);
            int height = options.outHeight;
            int width = options.outWidth;
            int inSampleSize = 2; // 默认像素压缩比例，压缩为原图的1/2
            int minLen = Math.min(height, width); // 原图的最小边长
            if (minLen > 100) { // 如果原始图像的最小边长大于100dp（此处单位我认为是dp，而非px）
                float ratio = (float) minLen / 100.0f; // 计算像素压缩比例
                inSampleSize = (int) ratio;
            }
            options.inJustDecodeBounds = false; // 计算好压缩比例后，这次可以去加载原图了
            options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例
            Bitmap bm = BitmapFactory.decodeFile(imagePath, options); // 解码文件
            Logger.i("------size: " + bm.getByteCount() + " width: " + bm.getWidth() + " heigth:" + bm.getHeight() + "---" + imagePath); // 输出图像数据


            String path = SDCardUtils.getSDCardPath() + "rong" + File.separator;
            File dirFile = new File(path);
            if (!dirFile.exists()) {
                dirFile.mkdir();
            }
            File myCaptureFile = new File(path + System.currentTimeMillis() + ".png");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
            bos.flush();
            bos.close();

//            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), myCaptureFile);
//            File myCaptureFile = new File(imagePath);
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), myCaptureFile);
//            RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file",myCaptureFile.getName(),RequestBody.create(MediaType.parse("image/png"),myCaptureFile)).build();
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", myCaptureFile.getName(), requestBody);
            uploadPhotoApi.setPart(part);
            HttpManager.getInstance().doHttpDeal(uploadPhotoApi);
        } catch (Exception io) {
        }
    }

    HttpOnNextListener uploadOnNextListener = new HttpOnNextListener<BaseResultEntity>() {

        @Override
        public void onNext(BaseResultEntity subjects) {

            UpdateUserLogoApi updateUserLogoApi = new UpdateUserLogoApi(UserSetAccountActivity.this,updateUserLogoNextListener);
            updateUserLogoApi.setArguments((String) subjects.getData(),MyApplication.getInstance().userLoginBean.getUserId());
            HttpManager.getInstance().doHttpDeal(updateUserLogoApi);
        }
    };

    HttpOnNextListener updateUserLogoNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_1000)){
                if (webView != null){
                    webView.loadUrl(url);
                }
                changePhoto = true;
            }
            Toast toast = Toast.makeText(UserSetAccountActivity.this, subjects.getMsg(), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    };



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && !TextUtils.isEmpty(url)){
            webView.reload();
            changeNickName = true;
        }else  if (requestCode == TAKE_CAMERA_PHOTO) {//拍一张照片进入剪裁
            CropImage.activity(Uri.fromFile(new File(path))).setGuidelines(CropImageView.Guidelines.OFF)
                    .setFixAspectRatio(true)
                    .setAspectRatio(1, 1)
                    .setCropShape(CropImageView.CropShape.RECTANGLE)
                    .setBorderCornerColor(Color.parseColor("#1e82d2"))
                    .setBorderCornerOffset(0)
                    .setBorderCornerThickness(10f)
                    .setBorderLineColor(Color.parseColor("#ff99cc00"))
                    .setBorderLineThickness(1.0f)
                    .setSnapRadius(0)
                    .setNoOutputImage(false)
                    .setOutputCompressFormat(Bitmap.CompressFormat.JPEG)
                    .setOutputCompressQuality(10)
                    .start(UserSetAccountActivity.this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (changeNickName || changePhoto){//如果修改了昵称
            EventBus.getDefault().post(new NickNameEvent());
        }
        EventBus.getDefault().removeAllStickyEvents();

    }

    public static Intent queryIntent(Context context, String url){
        Intent intent = new Intent(context,UserSetAccountActivity.class);
        intent.putExtra(ARG_URL,url);
        return intent;
    }
}
